import { useState, useTransition } from "react";
import PropTypes from 'prop-types'
function expensiveSearch(deferredQuery) {
    return Array(20000).fill(0).map((_, index) => `Result ${index} for ${deferredQuery}`)
}
function SearchResults({ results, isPending }) {
    return (
        <ul style={{ opacity: `${isPending ? 0.3 : 1}` }}>
            {
                results.map((result, index) => <li key={index}>{result}</li>)
            }
        </ul>
    )
}
SearchResults.propTypes = {
    results: PropTypes.array.isRequired,
    isPending: PropTypes.bool.isRequired
}
function App() {
    //定义搜索关键字
    const [query, setQuery] = useState('');
    //定义搜索的结果
    const [results, setResults] = useState([]);
    //useTransition创建过滤的状态和启动函数
    //isPending当前是否有正在被挂起的过度更新，或者说低优先级更新 startTransition启动更新的函数
    const [isPending, startTransition] = useTransition();
    const handleChange = (event) => {
        const value = event.target.value;
        setQuery(value);//先立刻进行高优先级更新
        //使用startTransition包装低优先级的更新
        startTransition(() => {
            //执行昂贵的搜索操作
            const searchResults = expensiveSearch(value);
            //更新搜索结果，因为此更新是在startTransition里执行的，所有的优先级比较低
            setResults(searchResults);
        });
    }
    return (
        <div>
            <input type="text" value={query} onChange={handleChange} />
            <SearchResults results={results} isPending={isPending} />
        </div>
    )

}
export default App;